package com.jacob.androidframe.controls;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerViewExtend extends RecyclerView implements RecyclerView.OnItemTouchListener
{
	private RecyclerViewExtend.OnItemClickListener mOnItemClickListener;
	private RecyclerViewExtend.OnItemLongClickListener mOnItemLongClickListener;

	private GestureDetector mGestureDetector;

	public RecyclerViewExtend(Context pContext)
	{
		this(pContext, null);
	}

	public RecyclerViewExtend(Context pContext, AttributeSet pAttrs)
	{
		this(pContext, pAttrs, 0);
	}

	public RecyclerViewExtend(Context pContext, AttributeSet pAttrs, int pDefStyle)
	{
		super(pContext, pAttrs, pDefStyle);
		mGestureDetector = new GestureDetector(pContext, new GestureDetector.SimpleOnGestureListener()
		{
			@Override
			public boolean onSingleTapUp(MotionEvent e)
			{
				return true;
			}

			@Override
			public void onLongPress(MotionEvent pE)
			{
				View _ItemView = findChildViewUnder(pE.getX(), pE.getY());

                if(_ItemView != null && mOnItemLongClickListener != null)
                {
                	mOnItemLongClickListener.onItemLongClick(RecyclerViewExtend.this, _ItemView);
                }
			}
		});

		addOnItemTouchListener(this);
	}

	@Override
	public boolean onInterceptTouchEvent(RecyclerView pRv, MotionEvent pE)
	{
		View _ItemView = pRv.findChildViewUnder(pE.getX(), pE.getY());
		if (_ItemView != null && mOnItemClickListener != null && mGestureDetector.onTouchEvent(pE)) {
			mOnItemClickListener.onItemClick(pRv, _ItemView);
		}
		return false;
	}

	@Override
	public void onTouchEvent(RecyclerView pRv, MotionEvent pE)
	{
	}
	
	public void setOnItemClickListener(RecyclerViewExtend.OnItemClickListener pOnItemClickListener)
	{
		mOnItemClickListener = pOnItemClickListener;
	}
	
	public void setOnItemLongClickListener(RecyclerViewExtend.OnItemLongClickListener pOnItemLongClickListener)
	{
		mOnItemLongClickListener = pOnItemLongClickListener;
	}

	public static interface OnItemClickListener
	{
		void onItemClick(RecyclerView pParent, View pItemView);
	}
	
	public static interface OnItemLongClickListener
	{
		void onItemLongClick(RecyclerView pParent, View pItemView);
	}
}
